package com.wolfstreet.wsonline.service.http;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketException;
import java.net.URL;
import java.util.Hashtable;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

import com.wolfstreet.wsonline.WSOApplication;
import com.wolfstreet.wsonline.Constant;
import com.wolfstreet.wsonline.exception.SDNotEnouchSpaceException;
import com.wolfstreet.wsonline.exception.SDUnavailableException;
import com.wolfstreet.wsonline.threadPool.TaskObject;
import com.wolfstreet.wsonline.util.FileHelper;
import com.wolfstreet.wsonline.util.JSONArray;
import com.wolfstreet.wsonline.util.JSONException;
import com.wolfstreet.wsonline.util.JSONObject;
import com.wolfstreet.wsonline.util.Util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;

/**
 * 网络连接类
 * 
 * @author sy
 * 
 */
public class ConnectionTask implements TaskObject {

	/**
	 * 普通的json消息连接请求
	 */
	public static final int CONNECT_TYPE_JSON = 0;

	/**
	 * 业务下载连接任务
	 */
	public static final int CONNECT_TYPE_DOWNLOAD = 1;

	/**
	 * 下载图片任务
	 */
	public static final int CONNECT_TYPE_BITMAP = 2;

	/**
	 * FORM
	 */
	public static final int CONNECT_TYPE_FORM = 3;

	/**
	 * post请求定义
	 */
	public static final int POST = 0;

	/**
	 * get请求定义
	 */
	public static final int GET = 1;

	/**
	 * 日志名
	 */
	// private static final String TAG = "--- ConnectionTask ---";

	/**
	 * 数据缓冲区的大小50K
	 */
	private static final int DATA_BUFFER_LEN = 1024 * 50;

	/**
	 * 图片极限值 10k
	 */
	private static final int DATA_IMG_LEN = 10240;

	/**
	 * 是否已经被取消的标志
	 */
	private boolean canceled = false;

	/**
	 * 是否已被暂停的标志
	 */
	private boolean paused = false;

	/**
	 * 请求类型，默认为POST
	 */
	private int requestType = POST;

	/**
	 * 超时时间(连接)
	 */
	private int connect_timeout = 5 * 1000;

	/**
	 * 超时时间(读取)
	 */
	private int read_timeout = 10 * 1000;

	/**
	 * 事件处理句柄
	 */
	private Handler handler;

	/**
	 * post请求消息体
	 */
	private byte[] dataBuf = null;

	/**
	 * Form请求消息体
	 */
	private List<NameValuePair> nameValuePairs = null;

	/**
	 * url地址
	 */
	private String httpUrl;

	/**
	 * 返回码
	 */
	private int responseCode;

	/**
	 * 网络状态回调接口
	 */
	private IStatusListener statusListener;

	/**
	 * http连接对象
	 */
	private HttpURLConnection conn;

	/**
	 * HttpClient 对象
	 */
	private HttpClient client;

	/**
	 * 输入流
	 */
	private InputStream is = null;

	/**
	 * 当前的连接类型 json请求、下载应用、下载图片
	 */
	private int connectType = CONNECT_TYPE_JSON;

	/**
	 * 存放请求头信息的Hashtable
	 */
	private Hashtable<String, String> sendHead = null;

	/**
	 * 断点
	 */
	private long breakpoint = 0L;

	/**
	 * 当为下载任务时，标志任务下载是否完成
	 */
	private boolean isDownloadSuccess = false;

	/**
	 * 文件对象
	 */
	private RandomAccessFile file;

	/**
	 * 下载资源包（用于路线图更新）
	 */
	private boolean isDownloadRes;

	/**
	 * SD卡回调同步锁
	 */
	private Object sdSyn = new Object();

	/**
	 * 默认构造方法
	 */
	public ConnectionTask() {

	}

	public ConnectionTask(IStatusListener statusListener, int connect_timeout,
			int read_timeout, Handler handler, int netType, boolean isGet) {
		this.statusListener = statusListener;
		this.connect_timeout = connect_timeout;
		this.read_timeout = read_timeout;
		this.handler = handler;
		this.connectType = netType;
		if (isGet) {
			requestType = GET;
		}
	}

	/**
	 * 设置下载类型
	 * 
	 * @param isDownload
	 */
	public void setDownloadType(boolean isDownloadRes) {
		this.isDownloadRes = isDownloadRes;
	}

	/**
	 * 设置断点值
	 */
	public void setBreakPoint(long breakpoint) {
		this.breakpoint = breakpoint;
	}

	/**
	 * 断点续传时获取继续下载时的断点信息
	 * 
	 * @return 已经下载的数据量
	 */
	public long getBreakPoint() {
		return breakpoint;
	}

	/**
	 * 设置断点
	 */
	public void setBreakPointHeader() {
		if (sendHead == null) {
			sendHead = new Hashtable<String, String>();
		}
		StringBuffer breakPointStr = new StringBuffer("bytes=");
		breakPointStr.append(breakpoint);
		breakPointStr.append("-");

		sendHead.put("RANGE", breakPointStr.toString());
		breakPointStr = null;
	}

	/**
	 * 取消连接任务
	 */
	public void cancelConnect() {
		canceled = true;
	}

	/**
	 * 判断用户是否已删除下载任务
	 * 
	 * @return 是否删除标志
	 */
	public boolean isCanceled() {
		return canceled;
	}

	/**
	 * 暂停连接任务
	 */
	public void pausedConnect() {
		paused = true;
	}

	/**
	 * 判断用户是否已暂停下载
	 * 
	 * @return 是否暂停下载标志
	 */
	public boolean isPaused() {
		return paused;
	}

	/**
	 * 运行联网任务
	 */
	public void runTask() {
		try {
			// 通知任务开始下载
			if (connectType == CONNECT_TYPE_DOWNLOAD) {
				isDownloadSuccess = false;
				startDownloadCallback();
			}

			// 执行网络连接操作（发送HTTP请求，并处理网络返回数据）
			connetionProcess();

			// 如果下载成功，回调到上层处理
			if (connectType == CONNECT_TYPE_DOWNLOAD && isDownloadSuccess) {
				successDownloadCallback();
			}
		} catch (SecurityException se) {
			hanlderException(se);
		} catch (InterruptedIOException e) {
			// 在connetionProcess()方法执行中或读写流中或打开连接时，打断会抛此异常
			if (canceled) {
				canceledCallback();
			} else if (paused) {
				// 暂停
				pausedCallback();
			} else {
				hanlderException(e);
			}
		} catch (InterruptedException e) {
			// 暂停取消时的打断异常
			if (canceled) {
				canceledCallback();
			} else if (paused) {
				pausedCallback();
			} else {
				hanlderException(e);
			}
		} catch (SocketException e) {
			// 无网络时会抛出该异常
			// System.out.println("SocketException" + e);
			hanlderException(e);
		} catch (UnsupportedEncodingException e) {
			setConnError(responseCode, e.getMessage());
		} catch (JSONException e) {
			setConnError(responseCode, e.getMessage());
		} catch (IOException e) {
			// 服务器响应异常会抛出该异常
			// System.out.println("IOException" + e);
			e.printStackTrace();
			hanlderException(e);
		} catch (Exception e) {
			// 其他异常
			// System.out.println("IOException" + e);
			e.printStackTrace();
			hanlderException(e);
		} catch (Error e) {
			// 错误处理
			if (connectType == CONNECT_TYPE_DOWNLOAD) {

			} else {
				setConnError(responseCode, e.toString());
			}
		} finally {
			clearNet();
		}

	}

	/**
	 * 异常处理
	 * 
	 * @param exception
	 *            异常对象
	 */
	private void hanlderException(Exception exception) {
		if (connectType == CONNECT_TYPE_DOWNLOAD) {
			setError(responseCode, exception.toString());
		} else {
			setConnError(responseCode, exception.toString());
		}
	}

	/**
	 * 实现了联网写读功能
	 * 
	 * @throws Exception
	 *             异常类
	 * @throws Error
	 *             错误类
	 */
	private void connetionProcess() throws Exception, Error {
		if (paused) {
			throw new InterruptedException();
		}

		if (connectType == CONNECT_TYPE_DOWNLOAD
				|| connectType == CONNECT_TYPE_BITMAP) {
			useUrlConnection();
		} else {
			useHttpClientConnection();
		}
	}

	/**
	 * @throws Exception
	 * @throws Error
	 */
	private void useUrlConnection() throws Exception, Error {
		// 构建连接
		URL url = new URL(httpUrl);
		String proxy_value = Util.getProxy(WSOApplication.getInstance());
		if (!proxy_value.equals("")) {
			Proxy proxy = new Proxy(Proxy.Type.HTTP,
					new InetSocketAddress(proxy_value, 80));
			conn = (HttpURLConnection) url.openConnection(proxy);
		} else {
			conn = (HttpURLConnection) url.openConnection();
		}

		conn.setConnectTimeout(connect_timeout);
		conn.setReadTimeout(read_timeout);
		// 不使用Cache
		conn.setUseCaches(false);

		// 设置请求类型
		if (requestType == POST) {
			conn.setRequestMethod("POST");
		} else {
			conn.setRequestMethod("GET");
		}

		if (sendHead != null && sendHead.containsKey("RANGE")) {
			conn.addRequestProperty("RANGE", (String) sendHead.get("RANGE"));
		}
		// 以内容实体方式发送请求参数
		if (requestType == POST && dataBuf != null) {
			// 发送POST请求必须设置允许输出
			conn.setDoOutput(true);

			// 维持长连接
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Length",
					String.valueOf(dataBuf.length));

			// 开始写入数据
			DataOutputStream outStream = new DataOutputStream(
					conn.getOutputStream());
			outStream.write(dataBuf);
			outStream.flush();
			outStream.close();
			outStream = null;
			if (canceled || paused) {
				throw new InterruptedException();
			}
		}
		responseCode = conn.getResponseCode();
		// 请求状态
		switch (responseCode) {
		case HttpStatus.SC_OK:
		case HttpStatus.SC_PARTIAL_CONTENT:

			break;
		default:
			throw new IOException("Connection response status not OK:"
					+ responseCode);
		}

		if (canceled || paused) {
			// Log.e("paused Before readdata", "");
			throw new InterruptedException();
		}

		// 读取数据
		readData();
	}

	/**
	 * JSON 数据传输
	 */
	private void useHttpClientConnection() throws Exception, Error {
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, connect_timeout);
		HttpConnectionParams.setSoTimeout(httpParams, read_timeout);
		client = new DefaultHttpClient(httpParams);

		String proxy_value = Util.getProxy(WSOApplication.getInstance());
		if (!proxy_value.equals("")) {
			HttpHost httpHost = new HttpHost(proxy_value, 80);
			client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
					httpHost);
		}
		HttpResponse httpResponse = null;
		// 设置请求类型
		if (requestType == POST) {
			// HttpPost连接对象
			HttpPost httpRequest = new HttpPost(httpUrl);

			HttpEntity httpentity = null;
			if (connectType == CONNECT_TYPE_JSON) {
				// httpRequest.setHeader("Content-Type",
				// "application/x-www-form-urlencoded");
				httpentity = new StringEntity(new String(dataBuf, HTTP.UTF_8),
						HTTP.UTF_8);
			} else {

			}

			// 请求httpRequest
			httpRequest.setEntity(httpentity);
			// 取得HttpResponse
			httpResponse = client.execute(httpRequest);
		} else {
			// HttpGet连接对象
			HttpGet httpRequest = new HttpGet(httpUrl);
			// 请求HttpClient，取得HttpResponse
			httpResponse = client.execute(httpRequest);
		}

		responseCode = httpResponse.getStatusLine().getStatusCode();
		// 请求状态
		switch (responseCode) {
		case HttpStatus.SC_OK:
		case HttpStatus.SC_PARTIAL_CONTENT:

			break;
		default:
			throw new IOException("Connection response status not OK:"
					+ responseCode);
		}

		// 读取数据
		readJsonData(httpResponse);
	}

	/**
	 * 读网络数据
	 * 
	 * @throws IOException
	 *             IO异常类
	 * @throws InterruptedException
	 *             中断异常类
	 */
	private void readData() throws Exception, IOException,
			InterruptedException, UnsupportedEncodingException, JSONException {

		long fileLenght = (long) conn.getContentLength();
		// 设置读取数据超时时间
		// conn.setReadTimeout(timeout);
		// 获取网络数据输入流
		is = conn.getInputStream();
		switch (connectType) {
		// 请求图片
		case CONNECT_TYPE_BITMAP:
			readBitmapData();
			break;
		// 下载请求
		case CONNECT_TYPE_DOWNLOAD:
			readDownloadData(fileLenght);
			break;
		default:
			break;
		}
	}

	/**
	 * 读取图片数据
	 */
	private void readBitmapData() {
		Bitmap bitmap = null;
		// 是否需要压缩流
		boolean needCompress = false;
		String suffix = httpUrl.substring(httpUrl.lastIndexOf("."),
				httpUrl.length()).toLowerCase();
		boolean isPNG = !suffix.equals(".jpg");

		if (is != null) {
			byte[] bt;
			try {
				bt = getBytes(is);
				bitmap = BitmapFactory.decodeByteArray(bt, 0, bt.length);
				if (bt.length > DATA_IMG_LEN) {
					// 大于10K
					needCompress = true;
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			bt = null;

			// 保存图片
			String tempPath = "";
			String md5_name = Util.getImgFileName(httpUrl);

			if (WSOApplication.getInstance().sdCardIsExist) {
				tempPath = WSOApplication.getInstance().SD_PATH
						+ Constant.IMG_PATH + md5_name;
			} else {
				tempPath = Constant.IMG_APP_PATH + md5_name;
			}

			byte[] data = Util.bitmapToBytes(bitmap, needCompress, !isPNG);
			FileHelper.writeImageCache(data, tempPath);
			try {
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// 回调bitmap
			handler.sendMessage(handler.obtainMessage(Constant.RETURN_BITMAP,
					0, 0, bitmap));
		}
		bitmap = null;
	}

	/**
	 * 将流转成字节 <功能详细描述>
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 * @see [类、类#方法、类#成员]
	 */
	private byte[] getBytes(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = 0;
		while ((len = is.read(b, 0, 1024)) != -1) {
			baos.write(b, 0, len);
			baos.flush();
		}
		byte[] bytes = baos.toByteArray();
		return bytes;
	}

	/**
	 * 读取JSON数据
	 * 
	 * @param httpResponse
	 * @throws Exception
	 * @throws InterruptedException
	 * @throws UnsupportedEncodingException
	 * @throws JSONException
	 */
	private void readJsonData(HttpResponse httpResponse) throws Exception,
			InterruptedException, UnsupportedEncodingException, JSONException {
		HttpEntity httpEntity = httpResponse.getEntity();
		InputStream is = httpEntity.getContent();

		ByteArrayOutputStream bos = null;
		try {
			bos = new ByteArrayOutputStream();
			int ch = 0;
			byte[] data = null;
			byte[] d = new byte[DATA_BUFFER_LEN];
			while ((ch = is.read(d)) != -1) {
				if (canceled) {
					data = bos.toByteArray();
					bos.close();
					throw new InterruptedException();
				}
				bos.write(d, 0, ch);

				if (canceled) {
					data = bos.toByteArray();
					bos.close();
					throw new InterruptedException();
				}
			}
			d = null;
			data = bos.toByteArray();
			JSONObject json = null;
			JSONArray jarray = null;
			// 把缓存以UTF_8编码格式转换成字符串
			String str = null;
			str = new String(data, HTTP.UTF_8);

			data = null;

			if (requestType == GET) {
				// get请求 返回非json格式
				if (handler != null) {
					handler.sendMessage(handler.obtainMessage(
							Constant.RETURN_JSONOBJECT, str));
				}
			} else {
				if (str.startsWith("[")) {
					jarray = new JSONArray(str);
				} else {
					json = new JSONObject(str);
				}

				if (handler != null) {
					if (jarray != null) {
						handler.sendMessage(handler.obtainMessage(
								Constant.RETURN_JSONARRAY, 0, 0, jarray));
					} else {
						handler.sendMessage(handler.obtainMessage(
								Constant.RETURN_JSONOBJECT, 0, 0, json));
					}
				}
			}
		} finally {
			if (bos != null) {
				bos.close();
				bos = null;
			}
			if (is != null) {
				is.close();
				is = null;
			}
		}
	}

	/**
	 * 读取下载业务的业务包数据
	 * 
	 * @param dataLen
	 *            数据长度
	 * @throws IOException
	 *             抛出IO异常供调用者捕捉
	 * @throws InterruptedException
	 *             抛出中断异常供调用者捕捉
	 */
	private void readDownloadData(long dataLen) throws IOException,
			InterruptedException {

		// 超时时间未到，连接成功停止超时任务
		// stopTimeoutTimer();

		long contentLen = 0L;
		// 从返回头中获取返回长度
		String contentLength = conn.getHeaderField("Content-Length");
		if (contentLength != null && contentLength.length() > 0) {
			try {
				contentLen = Long.parseLong(contentLength.trim());
				// Log.e("readDownloadData", "contentLen:" + contentLen);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			String contentRange = conn.getHeaderField("content-range");
			// Log.e("contentRange", "contentRange:" + contentRange);
			if (null != contentRange) {
				contentLen = Long.parseLong(Util.split2(contentRange, "/")[1])
						- breakpoint;
			}
		}

		try {
			// 从流中获取返回长度
			long isLen = (long) (is.available());

			// Log.e("readDownloadData", " " + "fileLenght:" + dataLen
			// + " conentLen:" + contentLen + " isLen:" + isLen);

			// 取3种返回长度的最大值作为真正的返回长度
			dataLen = dataLen > contentLen ? dataLen : contentLen;
			dataLen = dataLen > isLen ? dataLen : isLen;

			// Log.e("a: ", "breakpoint: " + breakpoint + " totalLen: "
			// + (dataLen + breakpoint));
			setDataLength(breakpoint, dataLen + breakpoint);

			// 存储已经下载的长度
			long getLen = 0;
			// 存储每次从网络层读取到的数据
			// 临时数据缓冲区
			int buffLen = 0;
			byte[] buff = new byte[DATA_BUFFER_LEN];
			byte[] tempBuff = null;

			// Thread.sleep(2000);

			// 创建文件
			createFile();

			while ((buffLen = is.read(buff)) != -1) {
				// 网络连接被暂停或取消，需要抛出中断异常，并关闭写文件线程
				if (canceled || paused) {
					// Log.e("paused 1 readdata", "");
					throw new InterruptedException();
				}

				// 如果没有读到数据就不需要写文件了
				if (buffLen <= 0) {
					continue;
				}

				// sd卡存在时将下载的数据写入文件
				if (WSOApplication.getInstance().sdCardIsExist) {
					// 将读到的数据写入文件，写文件成功后通知上层回调下载进度
					tempBuff = new byte[buffLen];
					System.arraycopy(buff, 0, tempBuff, 0, buffLen);
					int len = FileHelper.writeFile(file, tempBuff);
					if (len == FileHelper.ERROR) {
						throw new InterruptedException();
					} else {
						getLen += len;
						// 设置下载量（百分比）
						setDataLength(breakpoint + getLen, breakpoint + dataLen);
					}
				}
				// sd卡不存在直接抛出异常
				else {
					throw new InterruptedException();
				}

				// 网络连接被暂停或取消，需要抛出中断异常，并关闭写文件线程
				if (canceled || paused) {
					// Log.e("paused 2 readdata", "");
					throw new InterruptedException();
				}
			}
			buff = null;
			tempBuff = null;
			// Thread.sleep(2000);

			// 保证下载完了文本进度显示100%
			if (dataLen != getLen) {
				dataLen = getLen;
				setDataLength(breakpoint + getLen, breakpoint + dataLen);
			}
		} catch (IOException e) {
			throw new IOException();
		} catch (SDUnavailableException e) {
			throw new InterruptedException(e.getMessage());
		} catch (SDNotEnouchSpaceException e) {
			throw new InterruptedException(e.getMessage());
		}

		// 网络连接被暂停或取消，需要抛出中断异常，并关闭写文件线程
		if (paused || canceled) {
			// Log.e("paused 3 readdata", "");
			throw new InterruptedException();
		}

		// 标志下载完成
		isDownloadSuccess = true;
	}

	/**
	 * 关闭连接
	 */
	public void clearNet() {
		synchronized (sdSyn) {
			try {
				if (is != null) {
					is.close();
				}
				if (conn != null) {
					conn.disconnect();
				}
				if (file != null) {
					file.close();
				}
				if (nameValuePairs != null) {
					nameValuePairs.clear();
				}
				if (client != null) {
					client.getConnectionManager().shutdown();
				}
			} catch (Exception e) {
				// Log.e("clear net Exception:", e.toString());
			} finally {
				file = null;
				is = null;
				conn = null;
			}
		}
	}

	/**
	 * 无网络错误处理
	 * 
	 * @param responseCode
	 *            状态码
	 * @param exception
	 *            异常信息
	 */
	private void setConnError(int responseCode, String exception) {
		// 异常信息打印，正常情况下不会打出该日志
		// Log.e(TAG, "the responseCode is" + responseCode
		// + " and the exception is" + exception.toString());
		if (statusListener != null) {
			statusListener.onConnError(responseCode, exception);
		}
	}

	/**
	 * 设置错误回调
	 */
	private void setError(int responseCode, String exception) {
		// 异常信息打印，正常情况下不会打出该日志
		// Log.e(TAG, "the responseCode is" + responseCode
		// + " and the exception is" + exception.toString());
		// if (downloadItem != null) {
		// downloadItem.onError(responseCode, exception);
		// }
	}

	/**
	 * 设置取消回调
	 */
	private void canceledCallback() {
		// if (downloadItem != null) {
		// downloadItem.canceledCallback();
		// }
	}

	/**
	 * 设暂停回调
	 */
	private void pausedCallback() {
		// if (downloadItem != null) {
		// downloadItem.pausedCallback();
		// }
	}

	/**
	 * 设置下载回调
	 */
	private void startDownloadCallback() {
		// if (downloadItem != null) {
		// downloadItem.startDownloadCallback();
		// }
	}

	/**
	 * 下载完成回调通知接口
	 */
	private void successDownloadCallback() {
		// Log.e("successDownloadCallback", "success");
		// if (downloadItem != null) {
		// downloadItem.successDownloadCallback();
		// }
	}

	/**
	 * 回调网络接收的及时数据长度
	 * 
	 * @param getLength
	 *            已下载文件大小
	 * @param totalLength
	 *            文件的总大小
	 */
	public void setDataLength(long getLength, long totalLength) {
		// if (downloadItem != null) {
		// downloadItem.onProgressChanged(getLength, totalLength);
		// }
	}

	/**
	 * 设置POST内容
	 * 
	 * @param dataBuf
	 *            请求头参数
	 */
	public void setDataBuf(byte[] dataBuf) {
		this.dataBuf = dataBuf;
	}

	/**
	 * 设置Form内容
	 * 
	 * @param nameValuePairs
	 */
	public void setFormData(List<NameValuePair> nameValuePairs) {
		this.nameValuePairs = nameValuePairs;
	}

	/**
	 * 设置请求的url
	 * 
	 * @param httpUrl
	 *            连接地址
	 */
	public void setHttpUrl(String httpUrl) {
		this.httpUrl = httpUrl;
	}

	/**
	 * 设置请求类型
	 * 
	 * @param requestType
	 *            请求类型
	 */
	public void setRequestType(int requestType) {
		this.requestType = requestType;
	}

	/**
	 * 任务取消的回调接口方法
	 */
	public void onCancelTask() {
		canceled = true;
	}

	/**
	 * 获取网络连接任务对象请求的url
	 * 
	 * @return 请求的url
	 */
	public String getHttpUrl() {
		return httpUrl;
	}

	/**
	 * 任务请求响应回调接口
	 * 
	 * @param code
	 *            响应通知码
	 */
	public void onTaskResponse(int code) {

	}

	/**
	 * 创建下载文件目录
	 */
	private void createFile() {
		File tempFile = null;
		if (isDownloadRes) {
			if (Util.getHttpFileName(httpUrl) == null) {
				// 自定义文件名
				tempFile = FileHelper.createResFile("map.zip");
			} else {
				tempFile = FileHelper.createResFile(Util
						.getHttpFileName(httpUrl));
			}
		} else {
			// tempFile = FileHelper.createDownloadFile(downloadItem.savePath);
		}
		try {
			file = new RandomAccessFile(tempFile, "rw");
		} catch (IOException e) {
			// SysRecObservable.getInstance().deleteObserver(this);
			// Log.e("ConnectionTask:  ", e.getMessage());
		}
		tempFile = null;
	}

}
